#coding=utf-8 
from redis import *
import json

cache = Redis(host="127.0.0.1",port=6379,db=0)


# 插入SESSION
def set_session(_uid,_client,_name,_token):
    key = "session|{}".format(_client)
    ukey = "n2c|{}".format(_name)
    pipe = cache.pipeline()
    pipe.multi()
    pipe.delete(key)
    pipe.set(key, json.dumps({"name":_name,"uid":_uid,"client":_client,"token":_token}))
    pipe.set(ukey,_client)
    pipe.execute()
    
    
# 获取SESSION
def get_session(_client):
    key = "session|{}".format(_client)
    session = cache.get(key)
    if session:
        session = json.loads(session)
    return session



# 通过name获取SESSION
def get_session_by_name(_name):
    ukey = "n2c|{}".format(_name)
    client = cache.get(ukey)
    return get_session(client)


# 删除SESSION
def delete_session(_client):
    key = "session|{}".format(_client)
    session = cache.get(key)
    if session:
        session = json.loads(session)
        ukey = "n2c|{}".format(session["name"])
        cache.delete(ukey)
    cache.delete(key)
    
